package com.hl.tools.utils;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * Created by yuanhailong on 2021/10/28.
 */
public class CuratorUtils {

    private static PathChildrenCache cacheTask;

    private static CuratorFramework client;

    public static void initClient(String zkhoset,int timeout){
        RetryPolicy retryPolicy=new ExponentialBackoffRetry(3000,3);

        client= CuratorFrameworkFactory.builder()
                .retryPolicy(retryPolicy)
                .connectString(zkhoset)
                .sessionTimeoutMs(timeout)
                .connectionTimeoutMs(6000)
                .build();

        client.start();
    }


    public static void createNode(String tmpZNode,byte[] data) throws Exception{
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(tmpZNode,data);
    }

    public static void changeNodeData(String tmpZNode,byte[] data) throws Exception {
        client.setData().forPath(tmpZNode,data);
    }

    public static void delZNode(String tmpZNode) throws Exception {
        client.delete().deletingChildrenIfNeeded().forPath(tmpZNode);
    }

    public static String readZNode(String tmpZNode) throws Exception {
        byte[] bytes=client.getData().forPath(tmpZNode);
        return new String(bytes);
    }


    /**
     * 监控tmpZnode的变化
     * @param tmpZnode
     * @throws Exception
     */
    public static void startMonitorTask(String  tmpZnode) throws Exception{
        cacheTask=new PathChildrenCache(client,tmpZnode,true);

        cacheTask.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);

        cacheTask.getListenable().addListener((CuratorFramework curatorFramework,PathChildrenCacheEvent event)->{
            //TODO 根据具体要求编写监听代码
        });

    }






}
